/*
 * AIEngine a new generation network intrusion detection system.
 *
 * Copyright (C) 2013-2023  Luis Campo Giralte
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 * Written by Luis Campo Giralte <luis.camp0.2009@gmail.com> 
 *
 */
#pragma once
#ifndef SRC_CPUCYCLE_H_
#define SRC_CPUCYCLE_H_

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <ctime>

namespace aiengine {

class CPUCycle {
public:
        explicit CPUCycle(uint64_t *total_cpu_cycles) {

		total_cpu_cycles_ = total_cpu_cycles;
		start_cycles_ = compute();
	}

        virtual ~CPUCycle() {
		*total_cpu_cycles_ += compute() - start_cycles_;
	}
private:
	uint64_t compute() const {
#if defined(IS_DARWIN)
		return clock();
#else
  		uint32_t high, low;
    		
		__asm__ __volatile__ ("rdtsc" : "=a" (low), "=d" (high));
    		return ((uint64_t)high << 32) | low;
#endif
	}

	uint64_t start_cycles_;
	uint64_t *total_cpu_cycles_;
};

} // namespace aiengine

#endif  // SRC_CPUCYCLE_H_

